const app = getApp();
import UserService from '../../api/user';
Page({
  data: {
    url: '',
    password: '',        // 用户输入的旧密码
    newPassword: '',
    realPassword: '',
    message: '',
  },

  onEdit() {
    const { password, newPassword, realPassword } = this.data;

    if (!password || !newPassword || !realPassword) {
      this.setData({
        message: '所有字段都不能为空！'
      });
      return;
    }

    if (newPassword !== realPassword) {
      this.setData({
        message: '密码不一致，请重新输入！记得重输'
      });
      return;
    }

    const userId = wx.getStorageSync('userInfo').id;
    console.log(userId)
    UserService.changePassword({
      userId: userId,
      oldPassword: password,
      newPassword: newPassword
    }).then(res => {
      // 根据你的后端返回结构调整判断
      if (res.code === 200) {
        wx.showToast({
          title: '密码修改成功',
          icon: 'success',
          duration: 2000
        });
        // 清空输入
        this.setData({
          password: '',
          newPassword: '',
          realPassword: '',
          message: ''
        });
        // 返回上一页或跳转
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      } else {
        this.setData({
          message: res.message || '密码修改失败，请重试'
        });
      }
    }).catch(err => {
      console.error(err);
      this.setData({
        message: '请求失败，请检查网络或稍后再试'
      });
    });
  },

  click1() {
    wx.navigateBack({
      delta: 1
    });
  },

  oldPassword(e) {
    this.setData({
      password: e.detail.value
    });
  },

  newPassword(e) {
    this.setData({
      newPassword: e.detail.value
    });
  },

  realPassword(e) {
    this.setData({
      realPassword: e.detail.value
    });
  },

  goBack() {
    wx.switchTab({
      url: '../my/my',
    });
  },

  onLoad() {
    this.setData({
      url: app.globalData.URL
    });
  }
});
